﻿<%@ Application Language="C#" %>
<%@ Import Namespace="App_Code.Helpers" %>

<script runat="server">

    private const string DummyCacheItemKey = "DummyCacheItemKey";
    private HttpContext _currentContext;
        
    void Application_Start(object sender, EventArgs e) 
    {
        _currentContext = HttpContext.Current;

        //PluginHandler.DoWork(0, 0);
        //if (!RegisterCacheEntry())
        //{
        //    System.Diagnostics.Debug.WriteLine(string.Format("Failed when RegisterCacheEntry in Application_Start: {0}", DateTime.Now));
        //}
    }
    
    void Application_End(object sender, EventArgs e) 
    {
    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
    }

    void Session_Start(object sender, EventArgs e) 
    {
    }

    void Session_End(object sender, EventArgs e) 
    {
    }

    private bool RegisterCacheEntry()
    {
        try
        {
            if (null != _currentContext.Cache[DummyCacheItemKey]) return false;

            _currentContext.Cache.Add(
                DummyCacheItemKey, 
                "Test", 
                null,
                DateTime.MaxValue, TimeSpan.FromMinutes(1),
                CacheItemPriority.Normal,
                CacheItemRemovedCallback);

            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(string.Format("Exception in RegisterCacheEntry: {0} - {1}", DateTime.Now, ex.Message));
            return false;
        }
    }

    public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
    {
        try
        {
            System.Diagnostics.Debug.WriteLine(string.Format("Enter into CacheItemRemovedCallback: {0}", DateTime.Now));

            PluginHandler.DoWork(0,0);
            
            if(!RegisterCacheEntry())
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Failed when RegisterCacheEntry in CacheItemRemovedCallback: {0}", DateTime.Now));
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(string.Format("Exception in CacheItemRemovedCallback: {0} - {1}", DateTime.Now, ex.Message));
        }
    }

    //private void HitPage()
    //{
    //    System.Net.WebClient client = new System.Net.WebClient();
    //    client.DownloadData(DummyPageUrl);
    //}
       
</script>
